import React, { Component } from 'react';
import { Link } from 'react-router-dom';
import { Table } from 'antd';
import { connectRouter } from '../../../mixins/router';
import { Modal, Button } from 'antd';
import api from '../../../api/api';
import message from '@wanhu/antd-legacy/lib/message';
import { uploadFilesId } from "../../../createRequest";

// 会员卡片弹窗
import CustomerCart from '../../customerCenter/CustomerCard';

class InsuranceTable extends Component {
  constructor(props) {
    super(props);
    this.state = {
      visible: false,
      customerCardVisiblfe: false,
      currentCustomerId: null,
      getPagination: null,
      cardNum: '', // 体检卡号
      cardPW: '', // 体检卡密
      markUrl: '', // 预约地址
    };
  }


  tableChange = (pagination) => {
    this.props.pageChange(pagination);
    this.setState({
      getPagination: pagination,
    });
  };

  // 显示会员卡片
  showCustomerCard = (id) => {
    this.setState({
      customerCardVisible: true,
      currentCustomerId: id,
    });
  };
  hideCustomerCard = () => {
    this.setState({
      customerCardVisible: false,
    });
  };

  // 获取体检卡号
  getCardInfo = async ({InsuranceOrderProductId, mecSubscribeUrl}) => {
    const data = await api.getCardInfoData(InsuranceOrderProductId)
    if (data) {
      this.setState({
        cardNum: data.cardNo,
        cardPW: data.cardPassword,
        markUrl: mecSubscribeUrl,
        visible: true,
      });
    }else{
      message.error('无体检卡号!');
    }
  };

  // 上传体检报告
  uploadPdf = (row, e) => {
    const files = e.target.files[0];

    uploadFilesId(
      `_api/hd/medicalExaminationCards/uploadReport`,
      files,
      row.InsuranceOrderProductId,
      () => {},
    )
      .then((res) => {
        let xx = document.getElementById('file');
        xx.value = '';
        if (res.code === 0) {
          if (res.data.errorMessage) {
            message.error(res.data.errorMessage);
          } else {
            message.success('上传成功');
            this.props.searchDataFn();
          }
        } else {
          message.error(res.message);
        }
      })
      .catch((err) => {
        console.log('上传失败', err);
        message.error('上传失败');
      });

  };

  // 查看pdf
  viewPdf = (row)=>{
    window.open(`${row.mecResultPdf}`, '_blank');
  }

  // 查看体检卡号弹窗关闭
  handleCancel = () => {
    this.setState({
      visible: false,
    });
  };

  render() {
    const style = {
      textDecoration: 'underline',
      cursor: 'pointer',
      display: 'inline-block',
      marginRight: '10px',
      position: 'relative'
    };
    const uploadStyle = {
      position: 'absolute',
      top: '0',
      left: '0',
      width: '56px',
      height: '47px',
      opacity: '0',
    }

    const columns = [
      {
        title: '体检订单号',
        dataIndex: 'orderNo',
        key: 'orderNo',
        render: (text, row) => {
          return (
            <Link to={`/physicalExaminationInfo/${row.id}`}>
              <span className="clickable">{text}</span>
            </Link>
          );
        },
      },
      {
        title: '服务单号',
        dataIndex: 'insuranceOrderNo',
        key: 'insuranceOrderNo',
        render: (text, row) => {
          return (
            <Link to={`/patientInsuranceDetail/${row.insuranceOrderId}?r=`}>
              <span className="clickable">{text}</span>
            </Link>
          );
        },
      },

      {
        title: '服务对象',
        dataIndex: 'name',
        key: 'name',
        render: (text, row) => {
          return (
            <span
              style={{ textDecoration: 'underline', cursor: 'pointer' }}
              onClick={() => {
                this.showCustomerCard(row.insuredId);
              }}
            >
              {text}
            </span>
          );
        },
      },
      {
        title: '体检产品',
        dataIndex: 'insuranceProductName',
        key: 'insuranceProductName',
      },
      {
        title: '体检套餐',
        dataIndex: 'cardPackageTitle',
        key: 'cardPackageTitle',
      },
      {
        title: '体检单状态',
        dataIndex: 'status',
        key: 'status',
        render: (text) => {
          let temp = '';
          switch (text) {
            case 10:
              temp = '待激活';
              break;
            case 99:
              temp = '已完成';
              break;
            case 98:
              temp = '已终止';
              break;
            default:
              temp = '';
          }
          return temp;
        },
      },
      {
        title: '创建时间',
        dataIndex: 'createDate',
        width: 180,
        key: 'createDate',
      },
      {
        title: '操作',
        key: 'operation',
        render: (text, row, index) => {
          if (row.status === 99) {
            if (row.mecResultPdf) {
              return (
                <div>
                  <span style={style}>
                    上传报告
                    <input
                      type="file"
                      name="file"
                      id="file"
                      style={uploadStyle}
                      accept="image/jpeg, application/pdf"
                      onChange={(e) => this.uploadPdf(row, e)}
                    />
                  </span>
                  <span style={style} onClick={() => this.viewPdf(row, index)}>
                    查看报告
                  </span>
                </div>
              );
            } else {
              return (
                <div>
                  {
                    row.mecCardsClose === 1 ? (<span style={style} onClick={() => this.getCardInfo(row)}>获取体检卡 </span>) :''
                  }
                  <span style={style}>
                    上传报告
                    <input
                      type="file"
                      name="file"
                      id="file"
                      style={uploadStyle}
                      accept="image/jpeg, application/pdf"
                      onChange={(e) => this.uploadPdf(row, e)}
                    />
                  </span>
                </div>
              );
            }
          }
        },
      },
    ];
    let data = this.props.tableData;

    return (
      <div className="table-box block">
        <CustomerCart
          id={this.state.currentCustomerId}
          visible={this.state.customerCardVisible}
          hideCustomerCard={this.hideCustomerCard}
        ></CustomerCart>
        <Table
          columns={columns}
          dataSource={data.list}
          rowKey={(record) => record.id}
          pagination={{
            showSizeChanger: true,
            total: data.pageIndex !== 1 && data.count === data.pageSize ? data.count + 1 : data.count,
            showTotal: () => `第 ${data.pageIndex} 页`,
            pageSizeOptions: ['10', '20', '50', '100'],
            current: data.pageIndex,
            pageSize: data.pageSize,
          }}
          onChange={this.tableChange}
        />
        <Modal
          title="体检卡密"
          visible={this.state.visible}
          onCancel={this.handleCancel}
          footer={[
            <Button type="primary" onClick={this.handleCancel}>
              确定
            </Button>,
          ]}
        >
          <p style={{ lineHeight: '2.5em' }}>体检卡号： {this.state.cardNum}</p>
          <p style={{ lineHeight: '2.5em' }}>体检卡密码： {this.state.cardPW}</p>
          <p style={{ lineHeight: '2.5em' }}>预约地址： {this.state.markUrl ? this.state.markUrl : '无'}</p>
        </Modal>
      </div>
    );
  }
}

export default connectRouter(InsuranceTable);
